//
//  Extension+TextFiled.swift
//  ShiGuangJiaSwift
//
//  Created by 汪志浩 on 2023/3/3.
//

import Foundation

public extension UITextField {
    /**
     非中文：[^\\u4E00-\\u9FA5]
     非英文：[^A-Za-z]
     非数字：[^0-9]
     非中文或英文：[^A-Za-z\\u4E00-\\u9FA5]
     非英文或数字：[^A-Za-z0-9]
     非英文或数字或下划线：[^A-Za-z0-9_]
     非邮箱："[^A-Za-z0-9@.]"
     */
    /// 限制textField输入
     func limitInputWithPattern(pattern: String, _ limitCount: Int = -1) {
        // 非markedText才继续往下处理
        guard let _: UITextRange = self.markedTextRange else {
            // 当前光标的位置（后面会对其做修改）
            let cursorPostion = self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
            // 替换后的字符串
             var str = ""
            if pattern == "" {
                str = self.text!
            } else {
                str = self.text!.regularReplace(pattern: pattern, with: "")
            }
            // 如果长度超过限制则直接截断
            if limitCount >= 0, str.count > limitCount {
                str = String(str.prefix(limitCount))
            }
            self.text = str
            // 让光标停留在正确位置
            let targetPostion = self.position(from: self.endOfDocument, offset: cursorPostion)!
            self.selectedTextRange = self.textRange(from: targetPostion, to: targetPostion)
            return
        }
    }
}

public extension String {
    
    // 使用正则表达式替换
     func regularReplace(pattern: String, with: String, options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
}
